<?php

include_once 'i_shipping_carrier.php';

abstract class a_base_shipping_carrier extends a_base_model implements i_shipping_carrier {

    protected $order_object;
    protected $description;
    protected $carrier_id;
    protected $error_msg;

    public function __construct(stdClass $carrier_data_row) {
        parent::__construct(FALSE);
        $this->description = $carrier_data_row->description;
        $this->carrier_id = $carrier_data_row->carrier_id;
    }

    public function get_carrier_id() {
        return $this->carrier_id;
    }

    public function get_description() {
        return $this->description;
    }
    
    protected function _post($field_name) {
        return get_instance()->input->post($field_name);
    }

    public function get_error_message() {
        return $this->error_msg;
    }
    public function set_error_message($msg){
        $this->error_msg = $msg;
    }
    public function get_order_obj(){
        return $this->order_object;
    }
    public function  set_order_object(order_m_order $obj) {
        $this->order_object = $obj;;
    }
    
    public function get_rates() {
        if($this->order_object===NULL) show_error ("Order object not set for ".get_class ($this));
        $rates = NULL;
        $this->error_msg = "";//clearing out
        if($this->is_valid_for_rates()){
            $rates = $this->__get_rates();
            
        }else{
            $this->log($this->get_error_message());
        }
        return $rates;

    }

    /**
     * Saves order shipping rate information based on the shipping driver and 
     * selected valid rate.
     *
     * @param shipping_rates $sr
     * @param CI_Input $ci_post
     * @return bool
     */
    public function save_shipping_info(shipping_rates $sr,CI_Input $ci_post){
        if($this->order_object===NULL) show_error ("Order object not set for ".get_class ($this));
        $this->error_msg = "";//clearing out
        $validated_rate = $this->get_valid_rate_selection($sr, $ci_post);//NULL or rate object        
        
        if(is_a($validated_rate, "shipping_rate_object")){
            $this->__save_shipping_info($validated_rate);
            $shipping_service = new shipping_manager();
            $user_note = $ci_post->post('shipping_note') ? $ci_post->post('shipping_note') : "";
            $shipping_service->save_shipping_info($this->order_object,$validated_rate,$user_note);
            unset ($shipping_service);
            return TRUE;
        }elseif($validated_rate===NULL){
            logger::i()->error($this->get_error_message(), "shipping driver","checkout_shipping");
            return FALSE;
        }else{
            logger::i()->error("shipping rate object expected", "shipping driver","checkout_shipping");
            return FALSE;
        }
    }

}

?>